<!-- 注册页面 -->
<template>
  <div>
    <div class="nav">注册用户</div>
    <van-form validate-first @failed="onFailed" @submit="Register">
      <van-field
        v-model="userInfo.username"
        name="username"
        placeholder="用户名"
        label="用户名"
        :rules="myRules.usernameRules"
        required
      />
      <van-field
        v-model="userInfo.phone"
        name="phone"
        placeholder="手机号"
        label="手机号"
        :rules="myRules.phoneRules"
        required
      />
      <van-field
        v-model="userInfo.password"
        name="password"
        type="password"
        placeholder="密码"
        label="密码"
        :rules="myRules.passwordRules"
        required
      />
      <van-field name="radio" label="性别">
        <template #input>
          <van-radio-group v-model="userInfo.gender" direction="horizontal">
            <van-radio name="1">男</van-radio>
            <van-radio name="0">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field name="头像" label="头像">
        <template #input>
          <van-uploader v-model="pic" multiple :max-count="1" />
        </template>
      </van-field>

      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>


<script>
import { Toast } from "vant";
import { register } from "../../api/user";

export default {
  name: "RegisterIndex",
  data() {
    return {
      pic: [],
      userInfo: {
        username: "",
        password: "",
        phone: "",
        gender: "1",
      },
      myRules: {
        usernameRules: [
          {
            pattern: /^[a-zA-Z0-9_-]{3,16}$/,
            message: "请输入正确的用户名",
            required: true,
          },
        ],
        passwordRules: [
          {
            pattern: /[a-zA-Z0-9]{4,30}/,
            message: "请输入正确密码",
            required: true,
          },
        ],
        phoneRules: [
          {
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: "请输入正确的手机号",
            required: true,
          },
        ],
      },
    };
  },
  methods: {
    onFailed(errorInfo) {
      console.log("failed", errorInfo);
    },
    async Register() {
      try {
        Toast.loading({
          message: "加载中...",
          forbidClick: true,
        });
        let user = this.userInfo;
        let { data } = await register(user);
        if (data.status === 500) return Toast.fail(data.message);
        Toast.success("注册成功");
        console.log(this.userInfo);
        this.$router.replace("/login");
      } catch (err) {
        console.log(err);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.nav {
  line-height: 40px;
  background-color: rgb(25, 137, 250);
  color: white;
  text-align: center;
}
</style>